package com.permissionmanager.controller;

import com.permissionmanager.common.Result;
import com.permissionmanager.entity.Page;
import com.permissionmanager.entity.Perm;
import com.permissionmanager.entity.Role;
import com.permissionmanager.service.impl.PermServiceImpl;
import com.permissionmanager.service.impl.RoleServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * role控制层
 *
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/role")
public class RoleController {
    private final RoleServiceImpl roleService;
    private final PermServiceImpl permService;

    // 获取所有角色数据
    @GetMapping("/findAll")
    public Result findAll() {
        List<Role> role = roleService.findRole(null, null);
        return Result.success(role);
    }

    // 查询所有权限
    @GetMapping("/findPerm")
    public Result findPerm() {
        log.info("进入role所有权限查询功能！");
        List<Perm> list = permService.findAll();
        log.info("查询成功！");
        return Result.success(list);
    }

    // 分配权限
    @GetMapping("/allot/{permRoleId}")
    public Result allot(@PathVariable Integer permRoleId,
                        @RequestParam String permIds) {
        log.info("进入role分配权限功能！");
        List<Integer> permIdList = new ArrayList<>();
        for (String s : permIds.split(",")) {
            permIdList.add(Integer.valueOf(s));
        }
        roleService.allot(permRoleId,permIdList);
        log.info("分配权限成功！");
        return Result.success();
    }

    // 查询（pageNum、pageSize、name）
    @GetMapping("/findByPage")
    public Result findByPage(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam String roleName) {
        log.info("进入role分页查询功能！");
        Page<Role> page = roleService.findPage(pageNum,pageSize,roleName);
        log.info("查询成功！");
        return Result.success(page);
    }

    // 新增（roleName、permRoleId）
    @PostMapping("/add")
    public Result add(@RequestBody Role role) {
        log.info("进入role新增功能！");
        log.info("role-->{}",role);
        roleService.add(role);
        log.info("新增成功！");
        return Result.success();
    }

    // 修改 （id）
    @PutMapping("/update")
    public Result update(@RequestBody Role role) {
        log.info("进入role修改功能！");
        log.info("role-->{}",role);
        roleService.update(role);
        log.info("修改成功！");
        return Result.success();
    }

    // 删除（id）
    @DeleteMapping("/del/{id}")
    public Result del(@PathVariable Integer id) {
        log.info("进入role单条删除功能！");
        roleService.del(id);
        log.info("删除成功！");
        return Result.success();
    }
}
